package _case

import (
	"fmt"
	"sync"
	"time"
)

// 注意数据争用的情况，以及io输出串行化的情况，导致并行化计算变成伪并行，性能不会得到提高
func WaitGroupCase() {
	start := time.Now()
	for i := 0; i < 10000000000; i++ {
		sum(2, 5)
	}
	elapsed := time.Since(start)
	fmt.Println(elapsed)

	start = time.Now()
	wg := sync.WaitGroup{}
	for i := 0; i < 20; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < 500000000; j++ {
				sum(2, 5)
			}
		}()
	}
	wg.Wait()
	elapsed = time.Since(start)
	fmt.Println(elapsed)
}

func WaitGroupCase1() {
	ch := make(chan []int)
	start := time.Now()
	wg2 := sync.WaitGroup{}
	wg2.Add(1)
	go func() {
		defer wg2.Done()
		i := 0
		for item := range ch {
			fmt.Println(sum(item[0], item[1]))
			i++
		}
		time.Sleep(2 * time.Second)
		fmt.Println("数据处理完成，记录条数：", i)
	}()
	wg := &sync.WaitGroup{}
	for i := 0; i < 2; i++ {
		wg.Add(1)
		wg2.Add(1)
		//传递指针，防止拷贝
		go func(wg1 *sync.WaitGroup) {
			defer wg1.Done()
			defer wg2.Done()
			for j := 0; j < 500; j++ {
				ch <- []int{i, j}
			}
		}(wg)
	}
	wg.Wait()
	//关闭通道
	close(ch)
	wg2.Wait()
	elapsed := time.Since(start)
	fmt.Println(elapsed)
}

func sum(a, b int) int {
	return a + b
}
